﻿using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows.Forms;

namespace DownloadPhimBongngo
{
    public class Downloader
    {
        public delegate void ProgressChangedHandler(int downloadedFileCount);

        public event ProgressChangedHandler progressChangedEvent;

        protected void OnProgressChanged(int downloadedFileCount)
        {
            if (progressChangedEvent != null)
            {
                progressChangedEvent(downloadedFileCount);
            }
        }

        public void Download(string url, string filePath)
        {
            var client = new WebClient();
            int i = 1;

            var sw = new FileStream(filePath, FileMode.Create);
            var bw = new BinaryWriter(sw);

            while (true)
            {
                var fileUrl = url.Replace("(*)", i.ToString());

                try
                {
                    var data = client.DownloadData(fileUrl);
                    bw.Write(data);
                    bw.Flush();

                    OnProgressChanged(i);
                }
                catch (Exception ex)
                {
                    break;
                }

                i++;
            }

            bw.Close();
        }
    }
}
